/**
 * All Rights Reserved , Copyright (C) 2021 , 青岛鼎信通讯股份有限公司
 *
 *MpmProjectChangeController
 * 项目立项信息变更
 *
 * 修改纪录
 * 2021-07-14 版本：1.0 wudaliang 创建。
 * @version 版本：1.0
 * @author 作者：wudaliang
 * 创建日期：2021-07-14
 */

package com.topscomm.mpm.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.topscomm.basic.exception.MessageException;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.cbo.service.ICboDeptService;
import com.topscomm.mis.pojo.MisDeptHeaderEntity;
import com.topscomm.mis.service.impl.MisDeptHeaderService;
import com.topscomm.mpm.MpmSystemConst;
import com.topscomm.mpm.controller.auto.MpmProjectChangeControllerAuto;
import com.topscomm.mpm.pojo.MpmProjectChangeEntity;
import com.topscomm.mpm.service.IMpmProjectCustomerService;
import com.topscomm.mpm.service.impl.MpmProjectBidDateHistoryService;
import com.topscomm.mpm.service.impl.MpmProjectProductInfoHisService;
import com.topscomm.mpm.service.impl.MpmProjectProductOutInfoHisService;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.DateUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.tap.common.TapSystemConst.TapOperationTypeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: wudaliang
 * @date: 2021-07-14
 * @description:项目立项信息变更Controller
 * @modify:
 */
@RestController
@RequestMapping("mpm/projectChange")
public class MpmProjectChangeController extends MpmProjectChangeControllerAuto implements IMpmProjectChangeController {


	@Autowired
	private ICboDeptService cboDeptService;
	@Resource(name = "misDeptHeaderService")
	private MisDeptHeaderService misDeptHeaderService;
	@Autowired
	private IMpmProjectCustomerService mpmProjectCustomerService;
	@Autowired
	private MpmProjectBidDateHistoryService mpmProjectBidDateHistoryService;
	@Autowired
	private MpmProjectProductInfoHisService mpmProjectProductInfoHisService;
	@Autowired
	private MpmProjectProductOutInfoHisService mpmProjectProductOutInfoHisService;


	/**
	 * @author: wudaliang
	 * @date: 2021-07-14
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	protected String spellListSql(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" enabled=1 ");
		if (paraMap.containsKey("qry_state")) {
			String value = paraMap.get("qry_state").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and state in  ({0})", value);
		}
		if (paraMap.containsKey("qry_docno")) {
			String value = paraMap.get("qry_docno").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and docno like '%{0}%'", value);
		}
		if (paraMap.containsKey("qry_projectcode")) {
			String value = paraMap.get("qry_projectcode").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and projectcode2 = '{0}'", value);
		}
		if (paraMap.containsKey("qry_begindocdate")) {
			String value = paraMap.get("qry_begindocdate").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and docdate >= {0} ", SQLAdapter.toDateLong(value + " 00:00:00"));
		}
		if (paraMap.containsKey("qry_enddocdate")) {
			String value = paraMap.get("qry_enddocdate").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and docdate <= {0}", SQLAdapter.toDateLong(value + " 23:59:59"));
		}
		if (paraMap.containsKey("qry_deptname")) {
			String value = paraMap.get("qry_deptname").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (deptid in ( SELECT id from CboDept where fullname like '%{0}%'))", value);
		}
		if (paraMap.containsKey("qry_username")) {
			String value = paraMap.get("qry_username").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (username like '%{0}%')", value);
		}
		if (paraMap.containsKey("qry_deptcode")) {
			String value = paraMap.get("qry_deptcode").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and deptcode like '{0}%'", value);
		}
		if (paraMap.containsKey("qry_newadd")) {
			String value = paraMap.get("qry_newadd").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and newadd = '{0}' ", value);
		}
		if (paraMap.containsKey("qry_changetype")) {
			String value = paraMap.get("qry_changetype").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and changetype = '{0}' ", value);
		}
//		if (paraMap.containsKey("qry_state")) {
//			String value = paraMap.get("qry_state").toString();
//			if (!StringUtil.isEmpty(value))
//				sql.appendSingle(" and state={0}", value);
//		}
		if (paraMap.containsKey("qry_where")) {
			String value = paraMap.get("qry_where").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and {0}", value);
		}
		if (paraMap.containsKey("qry_notid")) {
			String value = paraMap.get("qry_notid").toString();
			if(!"0".equals(value)) {
				sql.appendSingle(" and id != {0}",value);
			}
		}
		if (this.getUserBean().getUser().getAdminlevel() < 1)// 管理员、超级管理员，不控制权限
		{
			String dataPession = service.getDataPermission(TapOperationTypeEnum.Select, "", this.getUserBean());
			if (StringUtil.isEmpty(dataPession))// 默认权限只能看本人，部门负责人为自己的部门和下级部门的数据
			{
//				String deptcodes_header = ConvertUtil.convertToString(this.getUserBean().getUser().getValue("deptcodes_header"));
//				if (StringUtil.isEmpty(deptcodes_header))
//					sql.appendSingle(" and (usercode = '{0}' or deptcode ='{1}' or deptcode = '{2}' )", this.getUserBean().getUser().getCode(), this.getUserBean().getDept().getCode(), this
//							.getUserBean().getWorkDept().getCode());
//				else
//					sql.appendSingle(" and (deptcode in ({0})  or usercode = '{1}' or deptcode ='{2}' or deptcode = '{3}' )", deptcodes_header, this.getUserBean().getUser().getCode(), this
//							.getUserBean().getDept().getCode(), this.getUserBean().getWorkDept().getCode());
			} else// 使用数据权限
			{
				sql.appendSingle(" and {0} ", dataPession);
			}
		}
		return sql.toString();
	}

	/**
	 * @author: wudaliang
	 * @date: 2021-07-14
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	@GetMapping(value = "/refList")
	public ResponseResult<Object> refList(@RequestParam(required = false) Map<String, Object> paraMap) {
		return super.refList(paraMap);
	}

	@Override
	@GetMapping(value = "/dataCodeList")
	public ResponseResult<Object> dataCodeList(@RequestParam(required = false) Map<String, Object> paraMap) {
		Map<String, Object> codeMap = new HashMap<String, Object>();
		List<Map<String, Object>> projectlevelList = datacodeCache.getCodeListMap("MpmProjectLevel", "", "sortcode");
		codeMap.put("projectlevelList", projectlevelList);
		List<Map<String, Object>> projectstateList = datacodeCache.getCodeListMap("MpmProjectState", "", "sortcode");
		codeMap.put("projectstateList", projectstateList);
		List<Map<String, Object>> mpmEndTypeList = datacodeCache.getCodeListMap("MpmEndType", "", "sortcode");
		codeMap.put("mpmEndTypeList", mpmEndTypeList);
		List<Map<String, Object>> mpmPmoChangeTypeList = datacodeCache.getCodeListMap("MpmPmoChangeType", "", "sortcode");
		codeMap.put("mpmPmoChangeTypeList", mpmPmoChangeTypeList);
		List<Map<String, Object>> mpmCeoApprovalTypeList = datacodeCache.getCodeListMap("MpmApprovalType", "", "sortcode");
		codeMap.put("mpmCeoApprovalTypeList", mpmCeoApprovalTypeList);
		List<Map<String, Object>> mpmProjectAbnormalStateList = datacodeCache.getCodeListMap("MpmProjectAbnormalState", "", "sortcode");
		codeMap.put("mpmProjectAbnormalStateList", mpmProjectAbnormalStateList);
		List<Map<String, Object>> MpmPurchasePatternList = datacodeCache.getCodeListMap("MpmPurchasePattern", "", "sortcode");
		codeMap.put("MpmPurchasePatternList", MpmPurchasePatternList);
		List<Map<String, Object>> projectSourceList = datacodeCache.getCodeListMap("ProjectSource", "", "sortcode");
		codeMap.put("projectSourceList", projectSourceList);
		// 产品线
		List<Map<String, Object>> productlinelist = datacodeCache.getCodeListMap("ProductLine", "", "sortcode");
		codeMap.put("productlineList", productlinelist);
		// 项目类型
		List<Map<String, Object>> pmoprojecttypeList = datacodeCache.getCodeListMap("MpmPMOProjectType", "", "sortcode");
		codeMap.put("pmoprojecttypeList",pmoprojecttypeList);
		// 产品大类编码
		List<Map<String, Object>> productcatalog1List = datacodeCache.getCodeListMap("ProductCatalog1", "", "sortcode");
		codeMap.put("productcatalog1List",productcatalog1List);
		// 产品中类编码
		List<Map<String, Object>> productcatalog2List = datacodeCache.getCodeListMap("ProductCatalog2", "", "sortcode");
		codeMap.put("productcatalog2List",productcatalog2List);
		return ResponseResult.ok(codeMap);
	}

	/**
	 *
	 * @description: 提交审批前
	 * @param dataMap
	 * @param paraMap
	 * @throws Exception
	 * @author: wudaliang
	 * @date: 2021-07-14
	 * @modify:
	 */
	@Override
	protected void beforeSubmit(Map<String, Object> dataMap, Map<String, Object> paraMap) throws Exception {
		super.beforeSubmit(dataMap, paraMap);
		StringBufferProxy mailtitle = new StringBufferProxy();
		mailtitle.appendSingle("{0}{1}于{2}提交项目立项信息变更申请,单据编号{3}! ", dataMap.get("dispdeptcode"), dataMap.get("username"), DateUtil.dateToString(new Date(), "yyyy-MM-dd"), dataMap.get("docno"));
		dataMap.put("maintitle", mailtitle.toString());
		this.service.update(paraMap);
	}

	/**
	 * @author: wudaliang
	 * @date: 2021-03-30
	 * @description: 修改项目级别变更历史字段
	 * @return: com.topscomm.pub.vo.ResponseResult<java.lang.Object>
	 * @modify:
	 */
	@PostMapping(value = "/updateLevelHistory")
	public ResponseResult<Object> updateLevelHistory(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			this.service.updateLevelHistory(paraMap);
			return ResponseResult.ok("成功");
		}catch (Exception e){
			throw new MessageException("修改‘项目级别变更历史’字段失败，请联系管理员");
		}
	}


	/**
	 * @author: wudaliang
	 * @date: 2021-07-08
	 * @param: paraMap
	 * @description: 返回林总和省总信息
	 * @return: com.topscomm.pub.vo.ResponseResult<java.lang.Object>
	 * @modify:
	 */
	@GetMapping("/queryCeo")
	public ResponseResult<Object> queryCeo(
		@RequestParam(required = false) Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		String managercode = "";
		if (paraMap.containsKey("managercode")) {
			//managercode为项目经理工号
			managercode = ConvertUtil.convertToString(paraMap.get("managercode"));
		} else {
			MpmProjectChangeEntity mpmProjectChangeEntity = this.service
				.queryById(paraMap.get("projectid").toString());
			managercode = mpmProjectChangeEntity.getProjectmanagercode2();
		}
		sql.appendSingle("  ID =(SELECT DEPTID from CBOUSER WHERE CODE='{0}') AND ENABLED=1 ", managercode);
		String code = cboDeptService.queryByWhere(sql.toString()).get(0).getCode();
		MisDeptHeaderEntity misDeptHeaderEntity = null;
		if (code.contains("_")) {
			sql.clear();
			sql.appendSingle("deptcode ='{0}' and category = 'CEO'", code.substring(0, code.indexOf('_') + 5));
			misDeptHeaderEntity = misDeptHeaderService.queryByWhere(sql.toString()).get(0);
		} else {
			sql.clear();
			sql.appendSingle("deptcode ='{0}' and category = 'CEO'", code.substring(0, 4));
			misDeptHeaderEntity = misDeptHeaderService.queryByWhere(sql.toString()).get(0);
		}
		List<MisDeptHeaderEntity> list = new ArrayList<>();
		sql.clear();
		sql.appendSingle("usercode ='0070' ");
		MisDeptHeaderEntity misDeptHeaderEntity1 = misDeptHeaderService.queryByWhere(sql.toString())
			.get(0);
		// 如果项目经理的领导是林总，需要去重
		if(misDeptHeaderEntity!=null&&misDeptHeaderEntity1!=null&&misDeptHeaderEntity.getUsercode().equals(misDeptHeaderEntity1.getUsercode())){
			list.add(misDeptHeaderEntity);
		}else{
			list.add(misDeptHeaderEntity);
			list.add(misDeptHeaderEntity1);
		}
		return ResponseResult.ok(list);

	}




	/**
	 * @Title: mainListExtraData
	 * @description: 手机端接口添加销售表数据项
	 * @param paraMap
	 * @param mainListData
	 * @author: lanjianwei
	 * @date: 2021年1月21日上午11:09:31
	 * @modify:
	 */
	@Override
	public void mainListExtraData(Map<String, Object> paraMap, Map<String, Object> mainListData) {
		String participatemoneyStr = ConvertUtil.convertToString(mainListData.get("participatemoney2"));
		mainListData.put("participatemoney2",formatMonty(participatemoneyStr,9,2));
		//涉及产品范围
		List<Map<String, Object>> productList = mpmProjectProductInfoHisService.queryMapByWhere(" changeid = '" + ConvertUtil.convertToString(paraMap.get("id")) + "'");
		StringBufferProxy productInfoPorxy = new StringBufferProxy();
		if (!CollectionUtil.isEmpty(productList)) {
			for (Map map : productList) {
				//产品名称，线索显示产品大类，机会点显示产品中类
				String cboItemCode = MpmSystemConst.MpmProjectSource.lead.equals(ConvertUtil.convertToString(mainListData.get("projectsource2"))) ? "ProductCatalog1" : "ProductCatalog2";
				String product = datacodeCache.getValueDynamic(cboItemCode, ConvertUtil.convertToString(map.get("productcode")),"code", "name");
				//产品金额
				String money = ConvertUtil.convertToString(map.get("fund"));
				if (money.length() > 0) {
					//金额格式化 追加万元
					money = formatMonty(money, 9, 2);
				}
				productInfoPorxy.appendLineSingle(product + "-" + money);
			}
		}
		mainListData.put("productrange2", productInfoPorxy.toString());
	}
	/**
	 * @author: wudaliang
	 * @date: 2021-06-22
	 * @param: value
	 * @param: maxDigit
	 * @param: minDigit
	 * @description:格式化金额
	 * @return: java.lang.String
	 * @modify:
	 */
	protected String formatMonty(String value, int maxDigit, int minDigit) {
		if (value != null && !value.equals("")) {
			try {
				BigDecimal bigDecimal = new BigDecimal(value);
				NumberFormat currency = NumberFormat.getNumberInstance();
				currency.setMaximumFractionDigits(maxDigit);
				currency.setMinimumFractionDigits(minDigit);
				String s = currency.format(bigDecimal.doubleValue());
				value = s + "万元";
				return value;
			} catch (Exception var7) {
				return value;
			}
		} else {
			return "";
		}
	}
	/**
	 * @author: 王兴华
	 * @date: 2021-07-14
	 * @description: 邀请决策
	 * @modify:
	 */
	@PutMapping("/updateInvitedUser")
	public ResponseResult<Object> updateInvitedUser(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			// 有邀请人的情况
			if (!StringUtil.isEmpty(ConvertUtil.convertToString(paraMap.get("invitedecisionusername2")))) {
				List<String> invitedUsers =  Arrays.asList(ConvertUtil.convertToString(paraMap.get("invitedecisionusername2")).split(","));
				List<String> invitedCodes = Arrays.asList(ConvertUtil.convertToString(paraMap.get("invitedecisionusercode2")).split(","));
				// 获取原始单据
				Map<String,Object> originalMap = this.service.queryMapById(ConvertUtil.convertToString(paraMap.get("id")));
				List<String> orginalUsers = Arrays.asList(ConvertUtil.convertToString(originalMap.get("decisionusername2")).split(","));
				List<String> orginalCodes = Arrays.asList(ConvertUtil.convertToString(originalMap.get("decisionusercode2")).split(","));
				// 遍历姓名去重
				List<String> useUserName = new ArrayList<>();
				for (int i=0; i<invitedUsers.size(); i++) {
					if(!orginalUsers.contains(invitedUsers.get(i))) {
						useUserName.add(invitedUsers.get(i));
					}
				}
				// 工号去重
				List<String> useUserCode = new ArrayList<>();
				for (int i=0; i<invitedCodes.size(); i++) {
					if (!orginalCodes.contains(invitedCodes.get(i))) {
						useUserCode.add(invitedCodes.get(i));
					} else {
						throw new ServiceException("邀请人已包含在决策组成员中，请重新选择");
					}
				}
				// 邀请人员
				String users = useUserName.stream().collect(Collectors.joining(","));
				String decisionusername = useUserName.size() > 0 ?
						ConvertUtil.convertToString(originalMap.get("decisionusername2")) + "," + users :
						ConvertUtil.convertToString(originalMap.get("decisionusername2"));
				// 邀请人员工号
				String codes = useUserCode.size() > 0 ?
						"," + useUserCode.stream().collect(Collectors.joining(",")) + "," : "";
				String decisionusercode = useUserCode.size() > 0 ?
						ConvertUtil.convertToString(originalMap.get("decisionusercode2")) + codes.substring(1) :
						ConvertUtil.convertToString(originalMap.get("decisionusercode2"));
				paraMap.put("decisionusercode2", decisionusercode);
				paraMap.put("decisionusername2", decisionusername);
				paraMap.put("invitedecisionusername2", users);
				paraMap.put("invitedecisionusercode2", codes);
			} else {
				// 删除值为空的key
				Iterator<String> keySetIterator = paraMap.keySet().iterator();
				while (keySetIterator.hasNext()) {
					if (StringUtil.isEmpty(ConvertUtil.convertToString(paraMap.get(keySetIterator.next())))) {
						keySetIterator.remove();
					}
				}
			}
			this.service.update(paraMap);
			return ResponseResult.ok("修改成功");
		} catch (Exception var3) {
			return this.handleControllerException(var3);
		}
	}

	@Override
	@PostMapping(value = "/insert")
	public ResponseResult<Object> insert(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			cboSystemLogService.insertMethodExecute(this.getClass().getName(), "insert", "方法执行");
			Map<String, Object> dataMap = paraMap;
			beforeInsert(dataMap, paraMap);
			MpmProjectChangeEntity entity = this.service.insert(paraMap);
			dataMap = entity.convertToMap();
			// 内外部产品历史子表信息
			paraMap.put("id", entity.getId());
			mpmProjectProductInfoHisService.removeAndAddRecord(paraMap);
			mpmProjectProductOutInfoHisService.removeAndAddRecord(paraMap);
			afterInsert(dataMap, paraMap);
			return ResponseResult.ok(dataMap);
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}

	@Override
	protected void afterLoad(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle("SOURCEID='{0}' and SOURCETYPE='{1}' ", paraMap.get("id"), MpmProjectChangeEntity.tableName);
		paraMap.put("customerlist", this.mpmProjectCustomerService.queryMapByWhere(sql.toString()));
		sql.clear();
		sql.appendSingle(" changeid = '{0}' ", ConvertUtil.convertToString(paraMap.get("id")));
		paraMap.put("productlist", mpmProjectProductInfoHisService.queryMapByWhere(sql.toString()));
		paraMap.put("productoutlist", mpmProjectProductOutInfoHisService.queryMapByWhere(sql.toString()));
	}
	/**
	 * @author: houyuhang
	 * @date: 2022-01-25
	 * @description: 新增立项变更时更新挂网招标日期
	 * @modify:
	 */
	@Override
	protected void afterInsert(Map<String, Object> dataMap, Map<String, Object> paraMap) throws Exception {
		super.afterInsert(dataMap, paraMap);
		// 新增挂网招标日期
//		long projectid = ConvertUtil.convertToLong(paraMap.get("projectIdForBidDate"));
//		long projecthistoryid = ConvertUtil.convertToLong(dataMap.get("id"));
//		mpmProjectBidDateHistoryService.addBidDateForChange(paraMap.get("projectBidDate"),projectid,projecthistoryid);
	}
	/**
	 * @author: houyuhang
	 * @date: 2022-01-25
	 * @description: 修改立项变更时更新挂网招标日期，并使enabled=0
	 * @modify:
	 */
	@Override
	protected void beforeUpdate(Map<String, Object> dataMap, Map<String, Object> paraMap) throws Exception {
		super.beforeUpdate(dataMap, paraMap);
		// 更新挂网招标日期
//		long id = ConvertUtil.convertToLong(paraMap.get("id"));
//		mpmProjectBidDateHistoryService.removeAndAddBidDate(paraMap.get("projectBidDate"),id);
	}

	/**
	 * @Title: submit
	 * @description:提交审批
	 * @param paraMap
	 * @return
	 * @author: lanjianwei
	 * @date: 2020年12月30日下午7:29:54
	 * @modify:
	 */
	@PutMapping(value = "/localSubmit")
	public ResponseResult<Object> localSubmit(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			Map<String, Object> dataMap = paraMap;
			this.service.executeLocalSubmit(paraMap);
			return ResponseResult.ok("提交成功");
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}

}

